<template>
  <div class="app-container">
    <!-- 查询 -->
    <el-row>
      <el-col class="mb-2">
        <el-input
          v-model="query.search_value"
          class="ya-search-value mr-6"
          placeholder="请输入公众号名称"
          clearable
        />
        <el-date-picker
          v-model="query.date_value"
          type="datetimerange"
          class="ya-date-value mr-6"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="dateShortcuts"
          popper-class="datetimerange-style"
          @change="search()"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="[new Date(2024, 1, 1, 0, 0, 0), new Date(2024, 1, 1, 23, 59, 59)]"
        />
        <el-button type="primary" @click="search()">查询</el-button>
        <el-button title="重置" @click="refresh()"
          >重置
          <!-- <svg-icon icon-class="refresh" /> -->
        </el-button>
        <el-button type="primary" @click="visible = true">添加</el-button>
      </el-col>
    </el-row>

    <!-- 列表 -->
    <el-table
      ref="table"
      v-loading="loading"
      :data="data"
      :height="height"
      stripe
      highlight-current-row
    >
      <el-table-column type="expand">
        <template #default="props">
          <h4 style="padding-left: 10px; margin: 8px 0">绑定的模板</h4>
          <el-table
            style="padding: 0 0 20px 0"
            :data="props.row.template_list"
            :border="childBorder"
          >
            <el-table-column label="模板类型" prop="type" width="200">
              <template #default="scopeChild">
                {{ scopeChild.row.type == 1 ? '方案推送' : '变化通知' }}
              </template>
            </el-table-column>
            <el-table-column label="模板ID" prop="template_id" />
            <el-table-column label="模板参数" prop="data" />
            <el-table-column label="操作" width="130">
              <template #default="scopeChild">
                <el-popconfirm
                  title="是否删除该绑定的模板?"
                  cancel-button-text="否"
                  confirm-button-text="是"
                  confirm-button-type="primary"
                  @confirm="templateDele(scopeChild.row)"
                >
                  <template #reference>
                    <el-link type="primary" class="mr-1" :underline="false"> 删除 </el-link>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="wechat_id" label="ID" width="80px" />
      <el-table-column prop="unique" label="唯一标识" width="120px" />
      <el-table-column prop="company" label="主体名称" show-overflow-tooltip />
      <el-table-column prop="title" label="公众号名称" width="120px" show-overflow-tooltip />
      <el-table-column prop="account" label="公众号账号" show-overflow-tooltip />
      <el-table-column prop="app_id" label="公众号ID" />
      <el-table-column prop="domain" label="专属域名" show-overflow-tooltip />
      <!-- <el-table-column prop="original" label="原始账号" show-overflow-tooltip /> -->
      <!-- <el-table-column prop="secret" label="公众号secret" show-overflow-tooltip /> -->
      <!-- <el-table-column prop="domain" label="主域名" show-overflow-tooltip /> -->
      <el-table-column prop="is_disable" label="禁用" width="100" show-overflow-tooltip>
        <template #default="scope">
          <el-switch
            v-model="scope.row.is_disable"
            :active-value="1"
            :inactive-value="0"
            @change="disable(scope.row)"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column prop="unique" label="二维码" show-overflow-tooltip /> -->
      <!-- <el-table-column prop="token" label="基础服务token" show-overflow-tooltip /> -->
      <!-- <el-table-column prop="aes_key" label="基础服务消息加解密密钥" show-overflow-tooltip /> -->
      <!-- ： 变化通知{{ props.row.changeCount}}个、 方案通知：{{ props.row.schemeCount }}个 -->
      <el-table-column label="模版数量" show-overflow-tooltip>
        <template #default="scope">
          <div v-if="scope.row.changeCount">变化通知: {{ scope.row.changeCount }}个</div>
          <div v-if="scope.row.schemeCount">方案推送: {{ scope.row.schemeCount }}个</div>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" show-overflow-tooltip />
      <el-table-column prop="remarks" label="备注" />
      <el-table-column label="操作" width="130" fixed="right">
        <template #default="scope">
          <el-link type="primary" class="mr-1" :underline="false" @click="info(scope.row)">
            修改
          </el-link>
          <el-popconfirm
            title="是否发布菜单?"
            cancel-button-text="否"
            confirm-button-text="是"
            confirm-button-type="primary"
            @confirm="pushMenu(scope.row)"
          >
            <template #reference>
              <el-link type="primary" class="mr-1" :underline="false"> 发布菜单 </el-link>
            </template>
          </el-popconfirm>
          <el-link type="primary" class="mr-1" :underline="false" @click="getBind(scope.row)">
            绑定商户
          </el-link>
          <el-link
            type="primary"
            class="mr-1"
            :underline="false"
            @click="getBindTemplate(scope.row)"
          >
            绑定模板
          </el-link>
          <el-popconfirm
            title="是否删除该数据?"
            cancel-button-text="否"
            confirm-button-text="是"
            confirm-button-type="primary"
            @confirm="dele(scope.row)"
          >
            <template #reference>
              <el-link type="primary" class="mr-1" :underline="false"> 删除 </el-link>
            </template>
          </el-popconfirm>
          <!-- <el-link type="primary" :underline="false"> 启用 </el-link> -->
          <!-- <el-link type="primary" :underline="false"> 清空 API 配额 </el-link> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 绑定模板 -->
    <el-dialog
      title="绑定模板"
      v-model="bindTemplatedialog"
      :close-on-click-modal="false"
      width="480"
      :before-close="handleClose"
    >
      <div>
        <el-form
          :model="templateRuleForm"
          :rules="templateRules"
          ref="templateRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="模板类型" prop="type">
            <el-select v-model="templateRuleForm.type" placeholder="请选择">
              <el-option label="方案推送" :value="1" />
              <el-option label="变化通知" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="模板ID" prop="template_id">
            <el-input v-model="templateRuleForm.template_id" />
          </el-form-item>
          <el-form-item label="模板参数" prop="data">
            <el-input type="textarea" rows="4" auto-height v-model="templateRuleForm.data" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button :loading="loading" @click="bindTemplatedialog = false">取消</el-button>
        <el-button :loading="loading" type="primary" @click="bindTemplateSubmit('templateRuleForm')"
          >确定</el-button
        >
      </template>
    </el-dialog>
    <!-- 绑定商户号 -->
    <el-dialog
      title="绑定商户"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      width="600"
      :before-close="handleClose"
    >
      <div>
        <el-transfer
          filterable
          filter-placeholder="请输入城市拼音"
          :filter-method="filterMethod"
          :titles="['商户列表', '已选']"
          v-model="value"
          :data="transferData"
        />
      </div>
      <template #footer>
        <el-button :loading="loading" @click="dialogVisible = false">取消</el-button>
        <el-button :loading="loading" type="primary" @click="bindSubmit">确定</el-button>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <pagination
      v-show="count > 0"
      v-model:total="count"
      v-model:page="query.page"
      v-model:limit="query.limit"
      @pagination="list"
    />

    <el-dialog
      v-model="visible"
      title="Tips"
      width="580px"
      :before-close="
        (done) => {
          ElMessageBox.confirm('是否关闭?')
            .then(() => {
              done()
            })
            .catch(() => {
              // catch error
            })
        }
      "
    >
      <el-form label-width="120px" :model="model" :rules="rules">
        <el-form-item label="公众号名称" prop="title">
          <el-input v-model="model.title" placeholder="请输入公众号名称" clearable />
        </el-form-item>
        <el-form-item label="公众号账号" prop="account">
          <el-input v-model="model.account" placeholder="请输入公众号名称" clearable />
        </el-form-item>
        <el-form-item label="公众号原始账号" prop="original">
          <el-input v-model="model.original" placeholder="请输入公众号名称" clearable />
        </el-form-item>
        <el-form-item label="appId" prop="app_id">
          <el-input v-model="model.app_id" placeholder="请输入公众号 appId" clearable />
        </el-form-item>
        <el-form-item label="appSecret" prop="secret">
          <el-input v-model="model.secret" placeholder="请输入公众号 appSecret" clearable />
        </el-form-item>
        <el-form-item label="token" prop="token">
          <el-input v-model="model.token" placeholder="请输入公众号 token" clearable />
        </el-form-item>
        <el-form-item label="消息加密密钥" prop="aes_key">
          <el-input v-model="model.aes_key" placeholder="请输入消息加密密钥" clearable />
        </el-form-item>
        <el-form-item label="校验文件名" prop="file_name">
          <el-input v-model="model.file_name" placeholder="请输入消息加密密钥" clearable />
        </el-form-item>
        <el-form-item label="主体名称">
          <el-input v-model="model.company" placeholder="请输入主体名称" clearable />
        </el-form-item>
        <el-form-item label="专属域名">
          <el-input v-model="model.domain" placeholder="请输入专属域名" clearable />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="model.remarks" placeholder="请输入管理员" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import screenHeight from '@/utils/screen-height'
import { getPageLimit } from '@/utils/settings'
import { shortcuts } from '@/utils/index'
import {
  list,
  disable,
  dele,
  add,
  info,
  edit,
  pushMenu,
  merchantList,
  merchantWechatAdd,
  wechatTemplateAdd,
  templateDele
} from '@/api/account/wechat'
export default {
  name: 'wechat',
  components: {},

  data() {
    return {
      dateShortcuts: shortcuts,
      // 模版参数
      templateRuleForm: {
        template_id: '',
        type: null,
        wechat_id: null,
        data: ''
      },
      changeCount: 0, //变化通知
      schemeCount: 0, //方案通知
      // 模板数据验证
      templateRules: {
        template_id: [{ required: true, message: '请输入模板ID', trigger: 'blur' }],
        data: [{ required: true, message: '请输入模板参数', trigger: 'blur' }],
        type: [
          {
            required: true,
            message: '请选择模版类型',
            trigger: 'change'
          }
        ]
      },

      bindTemplatedialog: false, //绑定模板
      dialogVisible: false, //绑定商户
      transferData: this.generateData(), //绑定商户列表
      value: [], //绑定商户的值
      bindItem: {}, //点击的对象数据
      filterMethod(query, item) {
        return item.label.indexOf(query) > -1
      },
      data: [], //table数据
      loading: false,
      height: 680, //table高度
      count: 0, //分页总条数
      query: {
        //接口入参
        page: 1,
        limit: getPageLimit(),
        search_field: 'title',
        search_value: '',
        search_exp: 'like',
        date_field: 'create_time',
        date_value: [] //默认当天
      },
      visible: false, //添加编辑弹窗
      // 添加编辑表单验证
      rules: {
        title: [{ required: true, message: '请输入公众号名称', trigger: 'blur' }],
        account: [{ required: true, message: '请输入公众号账号', trigger: 'blur' }],
        original: [{ required: true, message: '请输入公众号原始账号', trigger: 'blur' }],
        app_id: [{ required: true, message: '请输入公众号 appId', trigger: 'blur' }],
        secret: [{ required: true, message: '请输入公众号 appSecret', trigger: 'blur' }],
        token: [{ required: true, message: '请输入token', trigger: 'blur' }],
        aes_key: [{ required: true, message: '请输入消息加密密钥', trigger: 'blur' }],
        file_name: [{ required: true, message: '请输入校验文件名', trigger: 'blur' }]
      },
      model: {} //表单数据绑定
    }
  },
  created() {
    this.height = screenHeight()
    this.list()
  },
  methods: {
    // 绑定模版提交
    bindTemplateSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          wechatTemplateAdd(this.templateRuleForm).then((res) => {
            if (res.code == 200) {
              this.bindTemplatedialog = false
              ElMessage.success(res.msg)
              this.list()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 绑定模板弹窗
    getBindTemplate(item) {
      this.bindTemplatedialog = true
      this.bindItem = item
      this.templateRuleForm.wechat_id = item.wechat_id
    },
    // 绑定商户提交
    bindSubmit() {
      let ids = []
      this.value.forEach((element) => {
        ids.push(element)
      })
      merchantWechatAdd({
        wechat_id: this.bindItem.wechat_id,
        ids: ids
      }).then((res) => {
        if (res.code == 200) {
          this.dialogVisible = false
          ElMessage.success(res.msg)
          this.list()
        }
      })
    },
    // 绑定商户弹窗
    getBind(item) {
      this.dialogVisible = true
      this.bindItem = item
      this.value = item.pay_list
    },
    // 商户列表
    generateData() {
      const data = []
      merchantList({
        page: 1,
        is_disable: 0,
        limit: 100000
      }).then((res) => {
        res.data.list.forEach((element, index) => {
          data.push({
            label: `(${element.pay_type == 1 ? '微' : '支'})` + element.name,
            key: element.pay_id
          })
        })
      })
      return data
    },
    // 列表
    list() {
      this.loading = true
      list(this.query)
        .then((res) => {
          this.data = res.data.list
          this.data.forEach((element) => {
            element.changeCount = element.template_list.filter((i) => i.type == 2).length
            element.schemeCount = element.template_list.filter((i) => i.type != 2).length
          })
          console.log(this.data, 'this.data.template_list')
          this.count = res.data.count
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 搜索
    search() {
      this.query.page = 1
      this.list()
    },
    // 禁用
    disable(e) {
      disable({
        ids: [e.wechat_id],
        is_disable: e.is_disable
      })
        .then((res) => {
          ElMessage.success(res.msg)
          this.list()
        })
        .catch(() => {})
    },
    // 删除
    dele(e) {
      dele({
        ids: e.wechat_id
      })
        .then((res) => {
          ElMessage.success(res.msg)
          this.list()
        })
        .catch(() => {})
    },
    // 发布菜单
    pushMenu(e) {
      // pushMenu({
      //   wechat_id: e.wechat_id
      // })
      //   .then((res) => {
      //     ElMessage.success(res.msg)
      //   })
      //   .catch(() => {})
      axios({
        url: `${e.domain ? e.domain : 'http://xlm.feiyanfly.com'}/admin/account.Wechat/pushMenu`,
        method: 'post',
        data: {
          wechat_id: e.wechat_id
        },
        headers: { 'Content-Type': undefined }
      }).then((response) => {
        if (response.status === 200) {
          this.$message.error(response.data.msg)
        } else {
          this.$message.error('网络异常')
        }
      })
    },
    // 删除模板
    templateDele(e) {
      templateDele({
        ids: [e.id]
      })
        .then((res) => {
          ElMessage.success(res.msg)
          this.list()
        })
        .catch(() => {})
    },
    // 提交保存
    submit() {
      if (this.model.wechat_id) {
        this.edit()
      } else {
        this.add()
      }
    },
    // 添加
    add() {
      // 添加
      add(this.model).then((res) => {
        if (res.code == 200) {
          ElMessage.success('添加成功')
          this.list()
          this.visible = false
          this.model = {}
        }
      })
    },
    // 编辑
    edit() {
      // 添加
      edit(this.model).then((res) => {
        if (res.code == 200) {
          ElMessage.success('编辑成功')
          this.list()
          this.visible = false
          this.model = {}
        }
      })
    },
    // 编辑获取info
    info(item) {
      info({ wechat_id: item.wechat_id }).then((res) => {
        if (res.code == 200) {
          this.model = res.data
          this.visible = true
        }
      })
    },
    // 刷新
    refresh() {
      this.query = this.$options.data().query
      this.list()
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-popper {
  max-width: 50%;
}
</style>
